<?php
class download{
	private $d_id;
	
	public function __construct($id) {
			$this->d_id = $id;
	}
	
	public function check_id($id){	
			$sql_query = mysql_query("Select valid,date FROM ".DATABASE_TABLE_ID." WHERE id_generate = '".$id."'");
			while ($query = mysql_fetch_array($sql_query)){
				if($query['valid'] == "1"){
					if( ($query['date']+60*10) >= time() ){
						return true;
					}
					else{
						return false;
					}
				}
				else{
					return false;
				}
			}
			
	}
	
	public function file_generate_header(){
		$id = $this->d_id;
		$sql_query = mysql_query("Select film,user,server from ".DATABASE_TABLE_ID." WHERE id_generate = '".$id."' ORDER BY `id` ASC");
			while ($query = mysql_fetch_array($sql_query)){
				$file=$query['film'];
				$user=$query['user'];
				$server=$query['server'];
			}
		
		if (! $this->check_id($id)){
			mysql_query("INSERT INTO ".DATABASE_TABLE_LOG."(action,server,user,date) VALUES('MAUVAIS ID (tentative de hack)','".$server."' ,'".$user."','".time()."')") or die(mysql_error());
			print "Bad id";
			exit();
		}	
			
		$file2=file_to_path($file);
		if ($file2 == false){
			print "Bad name of file<br />";
			print $file;
			exit();
		}
		
		//gener header
		header("Pragma: public");                                                // vider le cache du navigateur
        header("Expires: 0");                                                    // ...
        header("Cache-Control:");                                                // ...
        header("Cache-Control: public");                                         // ... 
        header("Content-Description: File Transfer");    
		header('Content-Disposition: attachment; filename="'.$file.'";');
		header('Content-type:application/force-download');
		header("Content-Transfer-Encoding: binary");                             // methode du transfert  
        header("Content-Length: ".filesize($file2)."");                          // taille de téléchargement	
	
		$fp = fopen($file2, "r");
		//log
		//mysql_query("INSERT INTO ".DATABASE_TABLE_LOG."(action,server,user,date) VALUES('DL de ".$file."','".$server."' ,'".$user."','".time()."')") or die(mysql_error());
		while (!feof($fp))	{
		    echo fread($fp, 65536);
		    flush(); // this is essential for large downloads
		}
		fclose($fp);
		//desactive id
    	mysql_query("UPDATE ".DATABASE_TABLE_ID." SET `valid` = '0' WHERE id_generate = '".$id."' ");
		exit();
	
	} 
}

?>